package com.gr100.biz.api.shop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gr100.biz.api.bo.MetaObject;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by YFsoft on 16/4/12.
 */
public class ShopModel extends Model {

    private static final Log logger = Log.getLog("ShopModel");

    DbPro erp = Db.use("erp");


    void syncData(final Map<String,JSONArray> datas) throws Exception{

        logger.info(datas.toString());
        erp.tx(new IAtom() {
            @Override
            public boolean run() {
                ShopModel m = new ShopModel();
                try {
                    m.syncOrder(datas.get("Order"));                                //add status:8  OK
                    m.syncOrderGroupPay(datas.get("OrderGroupPay"));                // ok
                    m.syncOrderProduct(datas.get("OrderProduct"));                  //add status:8
                    m.syncProductStock(datas.get("ProductStock"));                  //OK
                    m.syncPStockchangeDetail(datas.get("PStockchangeDetail"));    //ok
                }catch(Exception e){
                    e.printStackTrace();
                    logger.error(e.getMessage());
                    return false;
                }

                return true;
            }
        });
    }

    void syncDayData(final Map<String,JSONArray> datas) throws Exception{
        logger.info(datas.toString());
        erp.tx(new IAtom() {
            @Override
            public boolean run() {
                ShopModel m = new ShopModel();
                try {
                    m.syncCheckStock(datas.get("CheckStock"));
                    m.syncOverallDaliy(datas.get("OverallDaliy"));
                    m.syncOverallDaliyDetail(datas.get("OverallDaliyDetail"));
                    m.syncPStockchangeDetail(datas.get("PStockchangeDetail"));
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    return false;
                }
                return true;
            }
        });
    }


    //object 转 Record

    List<Record> parse(JSONArray list){
        if(list == null) return null;
        if(list.size()<1) return null;
        List<Record> metaObjects = new ArrayList<Record>(list.size());
        for(Iterator<Object> it = list.iterator();it.hasNext();){
            String str = it.next().toString();
//            logger.info(str);
            JSONObject jo = JSON.parseObject(str);
            jo.remove("id");
            metaObjects.add(new Record().setColumns(new MetaObject(jo).getColumns()));
        }
        return metaObjects;
    }


    void syncCheckStock(JSONArray data) throws SQLException {
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        int[] ids = erp.batchSave("gr_sp_checkstock",metaObjects,metaObjects.size());
    }

    void syncOrder(JSONArray data) throws SQLException {
        //实时同步
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        List<Record> createObjects = new ArrayList<Record>();
        for(Record r : metaObjects){
            int syncStatus = r.getInt("syncStatus");
            r.remove("syncStatus");

//            判断syncstatus
            switch(syncStatus){
                case 0:
                    //新增
                    createObjects.add(r);
                    break;
                    //更新
                case 2:
                    erp.update("gr_sp_order","orderNum",r);
                    break;
                    //状态未知，需要判断
                case 8:
                    long count = erp.queryLong("select count(*) as c from gr_sp_order where orderNum= ?",r.get("orderNum").toString());
                    if(1 == count) {
                        //修改对象
                        erp.update("gr_sp_order","orderNum",r);
                    }else if(0 == count){
                        createObjects.add(r);
                    }else if(1 < count){
                        //已存在多条数据
                        erp.delete("gr_sp_order","orderNum",r);
                        //再插入
                        createObjects.add(r);
                    }
                    break;
            }
        }
        //添加对象
        int[] ids = erp.batchSave("gr_sp_order",createObjects,createObjects.size());
    }

    void syncOrderGroupPay(JSONArray data) throws SQLException {
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;

        List<Record> createObjects = new ArrayList<Record>();
        for(Record r : metaObjects){
            //数据存在则更新
            if(1 == erp.queryLong("select count(*) as c from gr_sp_grouppay where orderNum= ?",r.get("orderNum").toString())) {
                //修改对象
                erp.update("gr_sp_grouppay","orderNum",r);

            }else {
                createObjects.add(r);
            }

        }
        int[] ids = erp.batchSave("gr_sp_grouppay",createObjects,createObjects.size());

    }

    void syncOrderProduct(JSONArray data){
        //实时同步
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        List<Record> createObjects = new ArrayList<Record>();
        for(Record r : metaObjects){
            int syncStatus = r.getInt("syncStatus");
            r.remove("syncStatus");
//            判断syncstatus
            switch(syncStatus){
                case 0:
                    //新增
                    createObjects.add(r);
                    break;
                case 2:
                    //修改对象
                    erp.update("update gr_sp_orderproduct set pName = ? , count = ?,originPrice = ?,finnalPrice = ?,profit = ?,status = ? " +
                                    "where orderNum = ? and productId = ?",
                            r.get("pName"),r.get("count"),r.get("originPrice"),
                            r.get("finnalPrice"),r.get("profit"),r.get("status"),
                            r.get("orderNum").toString(), r.get("productId"));
                    break;
                //状态未知，需要判断
                case 8:
                    if(1 <= erp.queryLong("select count(*) as c from gr_sp_orderproduct where orderNum= ? and productId = ?",r.get("orderNum").toString(),r.get("productId"))) {
                        //修改对象
                        erp.update("update gr_sp_orderproduct set pName = ? , count = ?,originPrice = ?,finnalPrice = ?,profit = ?,status = ? " +
                                "where orderNum = ? and productId = ?",
                                r.get("pName"),r.get("count"),r.get("originPrice"),
                                r.get("finnalPrice"),r.get("profit"),r.get("status"),
                                r.get("orderNum").toString(), r.get("productId"));
                    }else {
                        createObjects.add(r);
                    }
                    break;
            }
        }
        //添加对象
        int[] ids = erp.batchSave("gr_sp_orderproduct",createObjects,createObjects.size());
    }

    void syncOverallDaliy(JSONArray data){
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        int[] ids = erp.batchSave("gr_sp_overalldaliy",metaObjects,metaObjects.size());
    }

    void syncOverallDaliyDetail(JSONArray data){
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        int[] ids = erp.batchSave("gr_sp_overalldaliydetail", metaObjects, metaObjects.size());
    }

    /**
     * 同步商品库存
     * @param data
     * @throws SQLException
     */
    void syncProductStock(JSONArray data) throws SQLException{
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        List<Record> createObjects = new ArrayList<Record>();
        for(Record r : metaObjects){
            //数据存在则更新
            if(1== erp.queryLong("select count(*) as c from gr_sp_productstock where shopId=? and productId=?",r.get("shopId"),r.get("productId"))) {
                //修改对象
                erp.update("update gr_sp_productstock set theoryValue = ?,diffeValue = ?,status = ? where shopId = ? and productId = ?",
                        r.get("theoryValue"),r.get("diffeValue"),r.get("status"),
                        r.get("shopId"), r.get("productId"));
            }else {
                createObjects.add(r);
            }
        }
        //添加对象
        int[] ids = erp.batchSave("gr_sp_productstock",createObjects,createObjects.size());

    }

    void syncPStockchangeDetail(JSONArray data){
        //实时同步
        if(null == data) return;
        List<Record> metaObjects = parse(data);
        if(null == metaObjects) return;
        List<Record> createObjects = new ArrayList<Record>();
        for(Record r : metaObjects){
            r.remove("syncStatus");
            //新增
            createObjects.add(r);
        }
        //添加对象
        int[] ids = erp.batchSave("gr_sp_pstockchangedetail",createObjects,createObjects.size());
    }
}
